﻿using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Net;
using System;

namespace ApplicationManager
{
    public class PortUtils
    {
        public static int GetAvailablePort(int startPort = 11001, int endPort = 11100)
        {
            IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners();
            IPEndPoint[] udpConnInfoArray = ipGlobalProperties.GetActiveUdpListeners();

            // 获取所有已使用的端口
            var usedPorts = tcpConnInfoArray.Concat(udpConnInfoArray)
                                          .Select(p => p.Port)
                                          .ToHashSet();

            // 在指定范围内查找未使用的端口
            for (int port = startPort; port <= endPort; port++)
            {
                if (!usedPorts.Contains(port))
                {
                    // 二次验证端口是否可用
                    if (IsPortAvailable(port))
                    {
                        return port;
                    }
                }
            }

            throw new Exception($"No available port found between {startPort} and {endPort}");
        }

        private static bool IsPortAvailable(int port)
        {
            try
            {
                // 尝试绑定到端口来验证是否可用
                var listener = new TcpListener(IPAddress.Loopback, port);
                listener.Start();
                listener.Stop();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
